package com.xujicheng.dingtalk.oauth2;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * 默认获取accessToken 的逻辑
 * @author: xujicheng
 * @project dingtalk-utils
 * @packge com.xujicheng.dingtalk.oauth2
 * @date: 2018/7/11 11:52
 * @description:
 */
@Slf4j
public class DefaultDingtalkToken implements DingtalkToken {

    private final String url;
    private final String corpid;
    private final String corpsecret;

    public DefaultDingtalkToken(String url,String corpId, String corpSecret){
        this.url = url;
        this.corpid = corpId;
        this.corpsecret = corpSecret;
    }

    @Override
    public String getToken() throws ApiException {
        Assert.isTrue(StringUtils.hasLength(corpid),"未配置dingtalk.corp.corpId");
        Assert.isTrue(StringUtils.hasLength(corpsecret),"未配置dingtalk.corp.corpSecret");
        DingTalkClient client = new DefaultDingTalkClient(url);
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setCorpid(corpid);
        request.setCorpsecret(corpsecret);
        request.setHttpMethod("GET");
        OapiGettokenResponse response = client.execute(request);
        if(response.isSuccess()) {
            return response.getAccessToken();
        }else{
            log.info("获取AccessToken失败，响应的错误信息：{},请求的信息[url]={},[corpid]={},[corpsecret]={}",response.getErrmsg(),url,corpid,corpsecret);
            throw new RuntimeException(response.getErrmsg());
        }
    }

    @Override
    public void renewal() throws ApiException {
        getToken();
    }

}
